package cn.mapway.plugin.sass;

import lombok.extern.slf4j.Slf4j;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ScssCompile
 * 编译scss文件.
 *
 * @author zhang
 */
@Mojo(name = "scss", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
@Slf4j
public class ScssCompile extends AbstractMojo {
    /**
     * 搜索文件后缀 缺省 scss|sass
     */
    @Parameter(defaultValue = "${project.basedir}/src/main/java", property = "apiLocation", required = true)
    private String suffices;

    /**
     * 搜索文件目录 缺省 ${project.basedir}/src/main
     */
    @Parameter(defaultValue = "${project.basedir}/src/main", property = "searchPath", required = true)
    private String searchPath;
    /**
     * sass编译器地址
     */
    @Parameter(defaultValue = "", property = "sassPath", required = true)
    private String sassPath;

    /**
     * 递归查找获取一个目录下所有子目录(及子目录的子目录)。子目录如果以 '.' 开头，将被忽略
     * <b>包含传入的目录</b>
     *
     * @param dir 目录
     * @return 子目录数组
     */
    public static List<File> scanDir(File dir, String filter) {
        List<File> files = new ArrayList<File>();
        if (dir.isDirectory()) {
            File[] files1 = Files.ls(dir, filter, Files.LsMode.FILE);
            if (files1 != null) {
                files.addAll(Lang.array2list(files1));
            }
            //目录 递归查找
            File[] files2 = Files.ls(dir, null, Files.LsMode.DIR);
            if (files2 != null) {
                for (File file : files2) {
                    scanDir(file, filter).forEach(files::add);
                }
            }
        }
        return files;
    }


    public static void main(String[] args) throws MojoExecutionException, MojoFailureException {
        ScssCompile scssCompile = new ScssCompile();
        scssCompile.searchPath = "E:\\dev\\imagebot\\ai-server-web\\src\\main";
        scssCompile.execute();
    }

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        log.info("ScssCompile");
        if (suffices == null || Strings.isBlank(suffices)) {
            suffices = "scss|sass";
        }
        File searchDir = new File(searchPath);
        if (!searchDir.exists()) {
            log.warn("sacc编译 找不到目录{}", searchPath);
            return;
        }
        List<File> files = scanDir(searchDir, "(" + suffices + ")$");
        if (files.size() == 0) {
            log.warn("目录{}下没有可编译的文件", searchPath);
            return;
        }
        log.info("找到可编译的文件 {}个", files.size());
        String prefix = "";
        if (Strings.isNotBlank(sassPath)) {
            prefix = sassPath;
        }
        if (prefix.length() > 0 && !prefix.endsWith("/")) {
            prefix += "/";
        }
        for (File file : files) {
            String fn = Files.getMajorName(file) + ".css";
            String fileName = file.getParentFile().getAbsolutePath() + File.separator + fn;
            String command = prefix + "sass " + file.getAbsolutePath() + ":" + fileName;
            log.info("执行命令 {}", command);
            try {
                StringBuilder output = Lang.execOutput(command);
                System.out.println(output);
            } catch (IOException e) {
                log.warn("=================attation====================");
                log.info("您可能需要安装 sass.js 编译器");
                log.info("1.安装 node windows https://nodejs.org/dist/v16.15.0/node-v16.15.0-x64.msi");
                log.info("        linux https://nodejs.org/en/download/ 查看其他下载");
                log.info("2.安装 sass.js 编译器 : npm install sass -g");
                e.printStackTrace();
            }
        }
    }
}
